package utilities;

import java.io.File;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

/**
 * 
 * @author ahosick Helper class for XJM.main.java
 */
public final class Writer {
	private static  Scan scan = new Scan();
	private static final Logger LOG = LoggerFactory.getLogger(Writer.class);

	//public Writer() {
	//}

	/**
	 * This method writes a DOM document to a file
	 * 
	 * @param doc
	 * @param filename
	 * @return
	 */  
	public static boolean writer(Document doc, String filename, boolean fromFile) {
		boolean result = true;
		boolean fileExists = false;
		Document newDoc = doc;
		String newString = filename;
		fileExists = DocumentUtilities.doesThisFileExist(filename);
		if (fileExists) { // TODO
			Scan scan = new Scan();
			String input;
			if(!fromFile){
				input = scan.getUserInput("Would you like the file " + filename + " to be overwritten? (Y/N)");
			} else {
				input = "y";
			}
			if ("Y".equalsIgnoreCase(input)) {
				writeFile(newDoc, newString);
				System.out.println("Your file has been overwritten!!");

			} else {

				result = false;
				System.out.println(" The file has not been overwritten. ");
			}
		} else if (!fileExists) {

			System.out
					.println("The outputfile did not exist and will be created!");
			writeFile(newDoc, newString);
		}
		return result;
	}
/**
 * 
 * @param doc
 * @param filename
 * @return the file
 */
	public static File writeFile(Document doc, String filename) {

		// Prepare the output file
		File file = new File(filename);
		try {
			// Prepare the DOM document for writing
			Source source = new DOMSource(doc);

			Result resultFile = new StreamResult(file);

			// Write the DOM document to the file
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			xformer.transform(source, resultFile);

		} catch (TransformerConfigurationException e) {
			LOG.error("***TransformerConfigurationException****");

		} catch (TransformerException e) {
			LOG.error("***TransformerException****");
		}

		return file;
	}
	/**
	 * getter and setter for scan for testing
	 * 
	 * @return
	 */
	public Scan getScan() {
		return scan;
	}

	public void setScan(Scan scan) {
		Writer.scan = scan;
	}
}